package com.example.bysj.Dao;
//201902104061徐中堂
import com.example.bysj.Service.StudentService;
import com.example.bysj.Service.TeacherService;
import com.example.bysj.domain.Student;
import com.example.bysj.domain.authority.Actor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.Statement;
//声明数据库访问类
@Repository("actorDao")
public class ActorDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    StudentService studentService;
    TeacherService teacherService;
    public int add(){
        KeyHolder keyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator preparedStatementCreator = con -> {
            PreparedStatement ps = con.prepareStatement("INSERT INTO actor () VALUES()", Statement.RETURN_GENERATED_KEYS);
            return ps;
        };
        jdbcTemplate.update(preparedStatementCreator, keyHolder);
        int id = keyHolder.getKey().intValue();
        return id;
    }

    //增加
    public boolean addActor() {
        //actor表中只有自增id字段，不需要参数
        String sql = "INSERT INTO actor () VALUES ()";
        int affectedRowNum = jdbcTemplate.update(sql);
        if (affectedRowNum != 1) {
            return false;
        } else {

            return true;
        }
    }
    //根据id查询
    public Actor find(int id){
        //先后在Student和Teacher中查找相应的id
        Actor desiredActor = null;
        //查询id对应的Student对象
        desiredActor = studentService.getOneById(id);
        if (desiredActor != null) {
            return desiredActor;
        }
        //查询id对应的Teacher对象
        desiredActor = teacherService.find(id);
        return desiredActor;
    }
}
